<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------


function get_by_curl($url)
{
    $curl= curl_init();
    // 设置URL和相应的选项
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    $result = curl_exec($curl);
    // 关闭cURL资源，并且释放系统资源
    curl_close($curl);
    return json_decode($result, true);
}


/**
 * @name 验证身份证
 * @time 2020-01-13
 * @desc 验证身份证格式
 * @author 大梦
 **/
function validation_filter_id_card($id_card)
{
    if (strlen($id_card) == 18) {
        return idcard_checksum18($id_card);
    } else if ((strlen($id_card) == 15)) {
        $id_card = idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    }
    return false;
}

// 计算身份证校验码，根据国家标准GB 11643-1999 
function idcard_verify_number($idcard_base)
{
    if (strlen($idcard_base) != 17) {
        return false;
    }
    // 加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    // 校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum           = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++) {
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }
    $mod           = $checksum % 11;
    $verify_number = $verify_number_list[$mod];
    return $verify_number;
}

// 将15位身份证升级到18位 
function idcard_15to18($idcard)
{
    if (strlen($idcard) != 15) {
        return false;
    } else {
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
            $idcard = substr($idcard, 0, 6) .
                '18' . substr($idcard, 6, 9);
        } else {
            $idcard = substr($idcard, 0, 6) .
                '19' . substr($idcard, 6, 9);
        }
    }
    $idcard = $idcard . idcard_verify_number($idcard);
    return $idcard;
}

// 18位身份证校验码有效性检查 
function idcard_checksum18($idcard)
{
    if (strlen($idcard) != 18) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))) {
        return false;
    } else {
        return true;
    }
}

function set_token()
{
    $v     = 1;
    $key   = mt_rand();
    $hash  = hash_hmac("sha1", $v . mt_rand() . time(), $key, true);
    $token = str_replace('=', '', strtr(base64_encode($hash), '+/', '-_'));
    return $token;
}

// 删除数组空字符串
function arrayFilter($arr)
{
    return array_filter($arr, function ($val) {
        if ($val === '' || $val === null) {
            return false;
        }
        return true;
    });
}

// 过滤空字符串 用于 Base 控制器 _search_filter
function filter_search_val($val)
{
    if ($val == '0') {
        return true;
    }
    if (empty($val)) {
        return false;
    }
    return true;
}

// list 转 tree
function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'pid', $child = '_child')
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用

        $refer = array();
        foreach ($list as $key => $data) {
            $list[$key]['spread'] = 'true';
            $refer[$data[$pk]]    = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string)$root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

// tree 转 list
function tree_to_list($tree, $level = 0, $pk = 'id', $pid = 'pid', $child = '_child')
{
    $list = array();
    if (is_array($tree)) {
        foreach ($tree as $val) {
            $val['level'] = $level;
            if (isset($val['_child'])) {
                $child = $val['_child'];
                if (is_array($child)) {
                    unset($val['_child']);
                    $list[] = $val;
                    $list   = array_merge($list, tree_to_list($child, $level + 1));
                }
            } else {
                $list[] = $val;
            }
        }
        return $list;
    }
}

// 树形菜单渲染
function tree_menu($tree, $level = 0)
{
    $level++;
    $html = "";

    if (!empty($tree) and is_array($tree)) {
        if ($level > 1) {
            $id   = $tree[0]['pid'];
            $html .= "<input type=\"checkbox\" id=\"chk_tree_$id\" checked=\"true\">";
            $html .= "<label for=\"chk_tree_$id\"><i class=\"fa fa-plus-square-o\"></i></label><ul>\r\n";
        } else {
            $html = "<ul>\r\n";
        }
        foreach ($tree as $val) {
            if (isset($val["name"])) {
                $title = $val["name"];
                $id    = $val["id"];
                if (isset($val['_child'])) {
                    $html = $html . "<li>\r\n<a node=\"$id\" >$title</a>\r\n";
                    $html = $html . tree_menu($val['_child'], $level);
                    $html = $html . "</li>\r\n";
                } else {
                    $html = $html . "<li>\r\n<a node=\"$id\" >$title</a>\r\n</li>\r\n";
                }
            }
        }
        $html = $html . "</ul>\r\n";
    }
    return $html;
}

// 获取系统配置

function get_system_config($name)
{
    $where[] = array('code', 'eq', $name);
    $list    = model('SystemConfig')->where($where)->value('val');
    return trim($list);
}

// option 渲染
function fill_option($list, $pk='id', $field='name', $data= [])
{
    $html = "<option></option>";
    if (is_array($list)) {
        foreach ($list as $key => $val) {
            if (is_array($val)) {
                $id   = $val[$pk];
                $name = $val[$field];
                if (in_array($id, $data)) {
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $html = $html . "<option value=\"{$id}\" $selected>{$name}</option>\r\n";
            } else {
                if (in_array($key, $data)) {
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $html = $html . "<option value=\"{$key}\" $selected>{$val}</option>\r\n";
            }
        }
    }
    return $html;
}

//  左侧导航

function left_menu($tree, $level = 0)
{
    $level++;
    $html = "";
    if (is_array($tree)) {
        $item_class = '';
        if ($level == 1) {
            $html       = '<ul class="layui-nav layui-nav-tree" lay-shrink="all" id="LAY-system-side-menu" lay-filter="layadmin-system-side-menu">' . "\r\n";
            $item_class = 'layui-nav-item';
        }
        foreach ($tree as $val) {
            if (isset($val["name"])) {
                $title = $val["name"];
                if (!empty($val["url"])) {
                    if (strpos($val['url'], 'http') !== false) {
                        $url = $val['url'];
                    } else {
                        $url = url($val['url']);
                    }
                } else {
                    $url = "#";
                }
                if (empty($val["id"])) {
                    $id = $val["name"];
                } else {
                    $id = $val["id"];
                }

                if (isset($val['_child'])) {
                    $html .= '<li class="' . $item_class . '">';
                    $html .= "<a node=\"$id\" href=\"" . "$url\"><i class=\"icon " . $val['icon'] . "\" ></i><cite>$title</cite><i class='count'></i></a>\r\n";
                    $html .= '<dl class="layui-nav-child">';
                    $html .= left_menu($val['_child'], $level);
                    $html = $html . "</dl>\r\n";
                    $html .= '</li>';
                } else {
                    $html .= '<li class="' . $item_class . '">';
                    $html .= "<a node=\"$id\" href=\"" . "$url\"><i class=\"icon " . $val['icon'] . "\" ></i><cite>$title</cite><i class='count'></i></a>\r\n";
                    $html .= '</li>';
                }
            }
        }
        if ($level == 1) {
            $html = $html . "</ul>\r\n";
        }
    }
    return $html;
}

// 获取用户ID
function get_user_id($emp_no = null)
{
    if (!empty($emp_no)) {
        $where_user[] = ['emp_no', 'eq', $emp_no];
        $user_id      = model('Admin')->where($where_user)->value('id');
    } else {
        $user_id = session(config('config.admin_auth_key'));
        $user_id = isset($user_id) ? $user_id : 0;
    }
    return $user_id;
}

// 获取返回地址
function get_return_url()
{
    $return_url = explode('$', cookie('return_url'));
    return end($return_url);
}

// hash 加密

function hash_func($value)
{
    return md5(md5($value));
}

// 获取扩展名
function get_file_ext_name($file)
{
    $arr = pathinfo($file);
    return $arr['extension'];
}


function think_encrypt($data, $key = '', $expire = 0)
{
    $auth_key = config('data_auth_key');
    $key      = md5(empty($key) ? $auth_key : $key);
    $data     = base64_encode($data);
    $x        = 0;
    $len      = strlen($data);
    $l        = strlen($key);
    $char     = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    $str = sprintf('%010d', $expire ? $expire + time() : 0);

    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }
    return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param string $key 加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */

function think_decrypt($data, $key = '')
{
    $auth_key = config('data_auth_key');
    $key      = md5(empty($key) ? $auth_key : $key);
    $data     = str_replace(array('-', '_'), array('+', '/'), $data);
    $mod4     = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data   = substr($data, 10);

    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = $str = '';

    for ($i = 0; $i < $len; $i++) {
        if ($x == $l)
            $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }

    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

function test($list, &$export)
{
    $export = array_filter(explode('|', $list));
    return '';
}

function slide_info($list)
{
    $img_list = array_filter(explode('|', $list));
    return $img_list;
}

function file_info($list)
{

    $file_list = array_filter(explode('|', $list));
    $file_list = array_map("think_decrypt", $file_list);

    if (!empty($file_list)) {
        $where[] = ['id', 'in', $file_list];
        $export  = model('File')->where($where)->select();
        $export->append(['file_icon']);
    } else {
        $export = '';
    }
    return $export;
}

//获取随机数
function get_randstr($length)
{
    $str     = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $len     = strlen($str) - 1;
    $randstr = '';
    for ($i = 0; $i < $length; $i++) {
        $num     = mt_rand(0, $len);
        $randstr .= $str[$num];
    }
    return $randstr;
}


function get_range($file_size)
{
    if (isset($_SERVER['HTTP_RANGE']) && !empty($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        $range = preg_replace('/[\s|,].*/', '', $range);
        $range = explode('-', substr($range, 6));
        if (count($range) < 2) {
            $range[1] = $file_size;
        }
        $range = array_combine(array('start', 'end'), $range);
        if (empty($range['start'])) {
            $range['start'] = 0;
        }
        if (empty($range['end'])) {
            $range['end'] = $file_size;
        }
        return $range;
    }
    return null;
}


function checked($id, $arr)
{
    if (!is_array($arr)) {
        $arr = explode(',', $arr);
    }

    if (in_array($id, $arr)) {
        return "checked='checked'";
    }
}

function notempty($val, $str)
{
    if (!empty($val)) {
        return $str;
    }
}

function in_val($val, $list, $str)
{
    if (!is_array($list)) {
        $list = array_filter(explode('|', $list));
    }

    if (in_array($val, $list)) {
        return $str;
    }
}


function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}


/**
 * 如果直接使用base64_encode和base64_decode方法的话，生成的字符串可能不适用URL地址
 * URL安全的字符串编码
 * @param $string
 * @return mixed|string
 */
function urlsafe_b64encode($string)
{
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;
}

/**
 * 如果直接使用base64_encode和base64_decode方法的话，生成的字符串可能不适用URL地址
 * URL安全的字符串解码
 * @param $string
 * @return bool|string
 */
function urlsafe_b64decode($string)
{
    $data = str_replace(array('-', '_'), array('+', '/'), $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

/**
 * 二维数组转置
 */
function rotate($a, $field = null)
{
    $b = array();
    if (is_array($a)) {
        foreach ($a as $val) {
            foreach ($val as $k => $v) {
                $b[$k][] = $v;
            }
        }
    }
    if (!empty($b) && !empty($field)) {
        return $b[$field];
    }
    return $b;
}


function map($val, $map)
{
    if (isset($map[$val])) {
        return $map[$val];
    }
    return '';
}

function create_order_no()
{
    $yCode   = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    return $orderSn;
}

function nonce_str($len = 8)
{
    static $seed = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    $str = '';
    for ($i = 0; $i < $len; $i++) {
        $rand = rand(0, count($seed) - 1);
        $temp = $seed[$rand];
        $str  .= $temp;
        unset($seed[$rand]);
        $seed = array_values($seed);
    }
    return $str;
}

// 总后台面包屑导航
function get_breadcrumb($node = null)
{
    if (empty($node)) {
        $node = cookie('current_node');
    }
    $menu = model('Menu')->find($node);
    $html = '';
    if (!empty($menu['pid'])) {
        $html .= get_breadcrumb($menu['pid']);
    }
    $html .= '<span lay-separator="">/</span><a href="' . url($menu['url']) . '"><cite>' . $menu['name'] . '</cite></a>';

    return $html;
}